package it.unibo.refolding.pico.stripchart.ui;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ZtListener implements MouseMotionListener, MouseListener {

	private static final Logger logger = Logger.getLogger(ZtListener.class.getSimpleName());

	private final ZtPanel panel;
	private int jpIndex;

	public ZtListener(ZtPanel panel) {
		this.panel = panel;
		jpIndex = -1;
	}

	@Override
	public void mouseDragged(MouseEvent e) {
		moveJunctionIfApplicable(e.getX());
	}

	@Override
	public void mouseMoved(MouseEvent e) {
	}

	@Override
	public void mouseClicked(MouseEvent e) {
	}

	@Override
	public void mouseEntered(MouseEvent e) {
	}

	@Override
	public void mouseExited(MouseEvent e) {
	}

	@Override
	public void mousePressed(MouseEvent e) {
		int x = e.getX(), y = e.getY();
		for (int j = 0; j < panel.h.modifiableJunctionPoints.size(); ++j) {
			int i = panel.h.modifiableJunctionPoints.getInt(j);
			if (i - ZtPanel.halfSquareSide <= x && x <= i + ZtPanel.halfSquareSide
					&& panel.y(i) - ZtPanel.halfSquareSide <= y
					&& y <= panel.y(i) + ZtPanel.halfSquareSide) {
				jpIndex = j;
				break;
			}
		}
		logger.log(Level.FINE, "jpIndex={0}", jpIndex);
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		moveJunctionIfApplicable(e.getX());
		jpIndex = -1;
	}

	private void moveJunctionIfApplicable(int x) {
		if (jpIndex != -1) {
			boolean leftOk = jpIndex == 0 || panel.h.modifiableJunctionPoints.getInt(jpIndex - 1) < x;
			boolean rightOk = jpIndex == panel.h.modifiableJunctionPoints.size() - 1
					|| panel.h.modifiableJunctionPoints.getInt(jpIndex + 1) > x;
			boolean change = panel.h.modifiableJunctionPoints.getInt(jpIndex) != x;
			logger.log(Level.FINE, "leftOk={0} rightOk={1} change={2}", new Object[] {leftOk,
					rightOk, change});
			if (leftOk & rightOk & change) {
				panel.h.setJunctionPoint(jpIndex, x);
				// TODO: Could repaint only affected regions.
				panel.repaint();
				panel.h.save();
			}
		}
	}
}
